package org.kl.bf.report.exporter;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kl.bf.service.ServiceException;

/**
 * @date 2014年6月9日
 * @thanksTo OneThin
 * @sourcefrom http://my.oschina.net/onethin/blog/14360
 */
public abstract class AbstractReportFileExporter {

	private static final Log logger = LogFactory.getLog(AbstractReportFileExporter.class);
	public static final String jasperReportPath = "/jasper/";// 报表的模板文件存放路径

	public enum ReportType {
		CSV, DOCX, HTML, PDF, PPTX, RTF, XLS, XLSX, XML
	}

	public void exportFromJasperFile(String fileName, final Collection<?> collection, Map<String, Object> reportParams,
			HttpServletRequest request, HttpServletResponse response) throws JRException, IOException {
		File sourceFile = new File(request.getSession().getServletContext().getRealPath(jasperReportPath + fileName + ".jasper"));
		System.out.println(request.getSession().getServletContext().getRealPath(jasperReportPath + fileName + ".jasper"));
		if (!sourceFile.exists()) {
			logger.error("报表文件" + sourceFile.getName() + "不存在");
			throw new ServiceException("报表文件" + sourceFile.getName() + "不存在");
		}
		JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(collection);
		JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFile.getAbsolutePath(), reportParams, beanCollectionDataSource);
		setHeader(response);
		export(jasperPrint, response.getOutputStream());
	}

	/**
	 * 生成相应格式的报表
	 * 
	 * @param jasperPrint
	 * @param os
	 * @throws JRException
	 */
	public void export(JasperPrint jasperPrint, OutputStream os) throws JRException {
	}

	/**
	 * 设置HTTP Header
	 * 
	 * @param jasperPrint
	 * @param response
	 * @throws JRException
	 */
	public void setHeader(HttpServletResponse response) throws JRException {
	}
}
